import TopComponent from "../components/topComponent";
import { useState } from "react";
import { Button, Form, Input, Toast } from "react-vant";
import { useNavigate } from "react-router-dom";
import { getUsers,handleSendEmail } from '../utils/api';
import './style/register.css'

const Register: React.FC = () => {
    type FormsValues = { email: string }
    const navigate = useNavigate();
    const [form] = Form.useForm();
    const [formValues, setFormValues] = useState<FormsValues>({ email: '' });
    const [isLoading, setIsLoading] = useState(false); // 新增加载状态
    const [emailError, setEmailError] = useState<string | null>(null);

    const validateEmail = (email: string) => {
        const basicPattern = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
        const isValid = basicPattern.test(email);

        if (!isValid) {
            setEmailError('请输入正确的邮箱');
            return false;
        } else {
            setEmailError(null);
            return true;
        }
    }

    const onValuesChange = () => {
        const values = form.getFieldsValue();
        setFormValues(values);

        if (values.email) {
            validateEmail(values.email);
        } else {
            setEmailError(null);
        }
    }

    const handleGoBack = () => {
        navigate('/login')
    }
    const handleDoLogin = async () => {
        // 验证邮箱
        if (!validateEmail(formValues.email)) {
            return;
        }
    
        try {
            // 立即显示加载状态
            setIsLoading(true);
            const loadingToast = Toast.loading({
                message: '正在验证...',
                forbidClick: true
            });
    
            // 准备API参数
            const params = {
                email: formValues.email
            };
    
            // 调用API
            const res = await getUsers(params);
            await handleSendEmail(params);
            console.log('API响应:', res);
            // 清除加载提示
            Toast.clear();
            if (res.data.code === 200) {
                // 显示成功提示，2秒后跳转
                const successToast = Toast.success({
                    message: '验证成功，即将跳转...',
                    duration: 2000
                });
                // 等待2秒后跳转
                await new Promise(resolve => setTimeout(resolve, 2000));
                navigate('/email', {
                    state: { 
                        email: formValues.email,
                        code:res.data.code
                     }
                });
            } else {
                // 显示错误提示，2秒后自动消失
                throw new Error(String(res.data.message || '验证失败'));
            }
        } catch (error: any) {
            console.error('API请求错误:', error);
            
            // 显示错误提示，2秒后自动消失
            Toast.fail({
                message: error.message || '网络错误，请重试',
                duration: 2000
            });
        } finally {
            // 无论成功失败都重置加载状态
            setIsLoading(false);
        }
    }

    return (
        <div>
            <TopComponent title="2" goBack={handleGoBack} />
            <div className="container-box">
                <span className="container-span">输入您的电子邮件地址以更改您的密码</span>
                <Form
                    form={form}
                    onFinish={handleDoLogin} // 直接绑定登录处理函数
                    onValuesChange={onValuesChange}
                    footer={
                        <div style={{ margin: '16px 16px 0' }}>
                            <Button
                                round
                                nativeType='submit'
                                type='primary'
                                block
                                loading={isLoading} // 绑定加载状态
                                disabled={!formValues.email || emailError || isLoading} // 完善禁用条件
                                onClick={handleDoLogin}
                            >
                                继续
                            </Button>
                        </div>
                    }
                >
                    <span className="container-span1">电子邮箱</span>
                    <Form.Item
                        name='email'
                        rules={[{ required: true, message: '请输入电子邮箱' }]}
                    >
                        <Input placeholder='输入您的电子邮箱' className="container-input" />
                    </Form.Item>
                    {emailError && <div className="error-message">{emailError}</div>}
                </Form>
            </div>
        </div>
    )
}

export default Register;